package servlet.events;

import java.io.IOException;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.User;

import dao.DAOFactory;

public class LogoutHandler extends EventHandler {
	@Override
	public void execute(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		HttpSession session = request.getSession();
		
		if (session.getAttribute("user") != null) {
			//update the last connected date
			DAOFactory.getUserDAO().update((User) session.getAttribute("user"));
			
			//remove user session
			session.removeAttribute("user"); //session.setAttribute("user", null);
			
			//update the numbers of authenticated users
			ServletContext application = request.getSession().getServletContext();
			
			Integer authenticatedUserCount = (Integer) application.getAttribute("authenticatedUserCount");
			
			if (authenticatedUserCount == null) {
				authenticatedUserCount = 1;
			}
			application.setAttribute("authenticatedUserCount", --authenticatedUserCount);
			
			//forward to logout.jsp
			forward(urlBundle.getString("LOGOUT_URL"), request, response);
			return;
		}
		//forward to login.jsp
		forward(urlBundle.getString("LOGIN_URL"), request, response);		
	}
}
